import 'dart:io';
import 'package:word_game/material/box.dart';
import 'package:yaml/yaml.dart';

import 'package:word_game/MergeThing.dart';
import 'package:word_game/battle/battle.dart';

import '../merge_thing_event.dart';
import '../search_thing_event.dart';
import 'thing.dart';
import 'use_event.dart';

class MaterialManager extends Object {
  static MaterialManager instance = MaterialManager();
  Map<String, Thing> materialMap={};

  appendMeterialsFromYAML(String fileName) {
    var content = File(fileName).readAsStringSync();
    var yaml = loadYaml(content);
    var materials = yaml['materials'] as List;
    for (var material in materials) {
      Thing obj;
      if (material['type'] == 'Box') {
        obj = Box(material);
      } else if (material['type'] == 'equipment') {
        obj = Equipment(material);
        (obj as Equipment).belongingPart = EquipmentPart.values[EquipmentPartHelper.valueStrs.indexOf(material['part'])];
      } else if (material['type'] == 'MergeThing') {
        obj = MergeThing(material);
      } else {
        obj = Thing(material);
      }
      if (material['canUse'] != null && material['canUse'] as bool) {
        obj.add(UseEvent());
      }
      if (material['canSearch'] != null && material['canSearch'] as bool) {
        obj.add(SearchThingEvent('essence_of_gold'));
      }
      if (material['mergeTargetCode'] != null && material['mergeTargetCode'].toString().length>0) {
        obj.add(MergeThingEvent(material['mergeTargetCode']));
      }
      materialMap[obj.code] = obj;
    }
  }

  Thing newMaterialWithCode(String code) {
    var obj = materialMap[code];
    // print('${obj.thingCode}');
    var result;
    if (obj is Box) {
      result = Box.copy(obj);
    } else if (obj is Equipment) {
      result = Equipment.copy(obj);
    } else if (obj is MergeThing) {
      result = MergeThing.copy(obj);
    } else {
      result = Thing.copy(obj);
    }
    // print('${result.thingCode}');
    return result;
  }
}